<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    width="60%"
    @register="registerModal"
    :title="getTitle"
  >
    <BasicForm @register="registerForm" class="!mx-auto" />

    <template #footer>
      <Spin :spinning="loading" :delay="200">
        <a-button @click="handleSubmit" type="primary">保存</a-button>
        <a-button @click="handleClose">取消</a-button>
      </Spin>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import { uploadSchema } from '/@/views/config-center/model-design/components/title.data';
  import { useFormDesignState } from '../../../hooks/useFormDesignState';
  import { getResourceInfo } from '/@/api/admin/resoure';
  import { toJson } from '/@/utils';

  // import { useMessage } from '/@/hooks/web/useMessage';
  // import { isObject } from '/@/utils/is';

  export default defineComponent({
    name: 'UploadConfigModal',
    components: { Spin, BasicModal, BasicForm },
    props: {
      isCustom: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['success', 'register'],
    setup() {
      const loading = ref(false);
      const { formConfig } = useFormDesignState();
      // updateSchema, validate
      const [registerForm, formActionType] = useForm({
        labelWidth: 120,
        baseColProps: { lg: 11, md: 23 },
        schemas: uploadSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal, changeLoading }] = useModalInner(
        async () => {
          formActionType.resetFields();
          let data = formConfig.value.currentItem!.attachment || {};
          if (formConfig.value.currentItem?.resourceCode) {
            const ret = await getResourceInfo(formConfig.value.currentItem?.resourceCode);

            data = toJson(ret.data);
          }
          formActionType.setFieldsValue(data);
        },
      );

      const getTitle = computed(() => '资源配置');

      async function handleSubmit() {
        try {
          loading.value = true;
          changeLoading(true);
          setModalProps({ confirmLoading: true });
          const values = await formActionType.validate();
          formConfig.value.currentItem!.attachment = values;
          handleClose();
        } finally {
          loading.value = false;
          changeLoading(false);
          setModalProps({ confirmLoading: false });
        }
      }

      async function handleClose() {
        closeModal();
      }
      return {
        loading,
        getTitle,
        registerModal,
        registerForm,
        handleSubmit,
        handleClose,
      };
    },
  });
</script>
